package DDD.RPCDemo1.src.cn.tedu.utils;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOUtils {
    private static Selector selector = null;
    private static SocketChannel sc = null;
    static{
        try {
            selector = Selector.open();
            sc = SocketChannel.open();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_CONNECT);
            sc.connect(new InetSocketAddress("127.0.0.1",9999));
            while(!sc.finishConnect()){}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte [] call(byte [] data){
        try {
            sc.register(selector,SelectionKey.OP_WRITE);
            while(true){
                selector.select();
                Set<SelectionKey> set = selector.selectedKeys();
                Iterator<SelectionKey> iterator = set.iterator();
                while(iterator.hasNext()){
                    SelectionKey sk = iterator.next();
                    if(sk.isWritable()){
                        byte[] data2 = ArrayUtils.concat((data.length + "#").getBytes(), data);
                        ByteBuffer buffer = ByteBuffer.wrap(data2);
                        while(buffer.hasRemaining()){
                            sc.write(buffer);
                        }
                        sc.register(selector,SelectionKey.OP_READ);
                    }else if(sk.isReadable()){
                        ByteBuffer temp = ByteBuffer.allocate(1);
                        String lenStr = "";
                        while(!lenStr.endsWith("#")){
                            lenStr += new String(temp.array());
                            temp.clear();
                        }
                        int len = Integer.parseInt(lenStr.substring(0,lenStr.length()-2));
                        ByteBuffer buffer = ByteBuffer.allocate(len);
                        while(buffer.hasRemaining()){
                            sc.read(buffer);
                        }
                        return buffer.array();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
